package net.wanho.service.impl;

import cn.hutool.core.util.IdUtil;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.ChineseCaptcha;
import com.wf.captcha.GifCaptcha;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import lombok.RequiredArgsConstructor;
import net.wanho.constant.CaptchaConstant;
import net.wanho.service.CaptchaService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Author：汤小洋
 * Date：2023-07-24 9:06
 * Description：<描述>
 */
@Service
@RequiredArgsConstructor
public class CaptchaServiceImpl  implements CaptchaService {

    private final RedisTemplate<String,Object> redisTemplate;

    /**
     * 生成验证码
     * @return
     */
    @Override
    public Map<String, String> captcha() {
        Captcha captcha = new ArithmeticCaptcha(111, 36); // 生成算术验证码，宽高为 111,36
        // new SpecCaptcha()
        // new GifCaptcha()
        // new ChineseCaptcha()
        System.out.println(captcha.text()); // 获取验证码的值
        // System.out.println()); // 获取验证码的流
        System.out.println(captcha.toBase64()); // 获取验证码的base64编码

        // 生成一个临时的用户id
        String uuid = IdUtil.simpleUUID();

        // 将验证码存入redis中
        redisTemplate.opsForValue().set(CaptchaConstant.CAPTCHA_PREFIX + uuid,captcha.text(), 2, TimeUnit.MINUTES);

        Map<String,String> map = new HashMap<>();
        map.put("uuid",uuid);
        map.put("img",captcha.toBase64());
        return map;

    }

    /**
     * 校验验证码
     * @param uuid
     * @param code
     */
    @Override
    public void check(String uuid, String code) throws Exception {
        String trueCode = (String) redisTemplate.opsForValue().get(CaptchaConstant.CAPTCHA_PREFIX + uuid);

        // 删除验证码
        redisTemplate.delete(CaptchaConstant.CAPTCHA_PREFIX + uuid);

        if(ObjectUtils.isEmpty(trueCode)){
            throw new Exception("验证码已过期");
        }
        if (!trueCode.equals(code)){
            throw new Exception("验证码错误");
        }
    }
}
